package com.dubbo.rpc.registry;

import com.dubbo.rpc.common.Constants;
import com.dubbo.rpc.config.ConfigService;
import org.I0Itec.zkclient.ZkClient;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * 服务注册
 * @author liuxin
 * @date 2021/10/10 8:43
 */
@Component
public class ServiceRegistry {

    @Resource
    private ConfigService configService;

    private ZkClient zkClient;

    @PostConstruct
    public void init() {
        try {
            // 初始化 zk 连接
            zkClient = new ZkClient(configService.getZkHost(), Constants.ZK_SESSION_TIME_OUT, Constants.ZK_CONNECTION_TIME_OUT);
            System.err.println("zkClient created");
        } catch (Exception e) {
            System.err.println(ExceptionUtils.getStackTrace(e));
        }
    }


    public void register(String serviceName, String serviceAddress) {
        // 创建 registry 节点, 持久
        if (!zkClient.exists(Constants.ZK_REGISTRY_PATH)) {
            System.err.println("创建 registry 持久节点: " + Constants.ZK_REGISTRY_PATH);
            zkClient.createPersistent(Constants.ZK_REGISTRY_PATH);
        }

        // 创建 service 节点, 持久
        String servicePath = Constants.ZK_REGISTRY_PATH + Constants.ZK_PATH_DELIMITER + serviceName;
        if (!zkClient.exists(servicePath)) {
            System.err.println("创建持久 service 节点: " + servicePath);
            zkClient.createPersistent(servicePath);
        }

        // 创建 address 节点, 临时
        String addressPath = servicePath + Constants.ZK_PATH_DELIMITER + "address-";
        String ephemeralSequential = zkClient.createEphemeralSequential(addressPath, serviceAddress);
        System.err.println("创建 address 临时节点：" + ephemeralSequential);
    }

}
